package com.newenergy.wisehome.gateway.family;


import android.content.Context;
import android.os.Handler;
import android.support.v4.app.Fragment;
import android.support.v7.widget.DividerItemDecoration;
import android.support.v7.widget.LinearLayoutManager;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.TextView;

import com.jude.easyrecyclerview.EasyRecyclerView;
import com.newenergy.wisehome.R;
import com.newenergy.wisehome.common.manager.MyThreadManager;
import com.newenergy.wisehome.data.bean.BLDeviceInfo;
import com.newenergy.wisehome.data.bean.Family;
import com.newenergy.wisehome.data.ormlite.dao.BLDeviceInfoDao;
import com.newenergy.wisehome.data.ormlite.dao.FamilyDao;
import com.newenergy.wisehome.gateway.adapter.ManageBLFamilyAdapter;
import com.newenergy.wisehome.gateway.common.BLModelUtil;
import com.newenergy.wisehome.gateway.manager.BLLocalFamilyManager;
import com.newenergy.wisehome.ui.fragment.BaseFragment;

import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;
import cn.com.broadlink.base.BLBaseResult;
import cn.com.broadlink.family.BLFamily;
import cn.com.broadlink.family.params.BLFamilyAllInfo;
import cn.com.broadlink.family.params.BLFamilyInfo;
import cn.com.broadlink.sdk.data.controller.BLDNADevice;

/**
 * A simple {@link Fragment} subclass.
 */
public class ManageBLFamilyFragment extends BaseFragment implements ManageBLFamilyAdapter.ManageBLFamilyListener {


    @BindView(R.id.tv_page)
    TextView mTvPage;
    @BindView(R.id.recyclerView)
    EasyRecyclerView mRecyclerView;
    private ManageBLFamilyAdapter mAdapter;
    private LinearLayoutManager mLayoutManager;
    private int mCurrPosition = 0;
    private Family mFamily;
    private boolean showUnBinderLoading = true;

    private Handler mHandler = new Handler();

    @Override
    public int getLayoutId() {
        return R.layout.fragment_manage_blfamily;
    }

    @Override
    public void init(View rootView) {
        mTvPage.setText("网关家庭管理");
        initRecycleView();
    }

    @Override
    public void onResume() {
        super.onResume();
        refreshListData();
        getNoFamilyLocalBLDevice();
    }


    private void refreshListData() {
        mAdapter.clear();
        FamilyDao familyDao = new FamilyDao(getContext());
        List<Family> families = familyDao.getFamiliesByType(1);
        if (families != null && families.size() > 0) {
            mAdapter.addAll(families);
            mCurrPosition = 0;
//            setCurrentItem();
        }
    }

    private void getNoFamilyLocalBLDevice() {
        BLDeviceInfoDao deviceInfoDao = new BLDeviceInfoDao(getContext());
        List<BLDeviceInfo> deviceInfos = deviceInfoDao.getAllBLDeviceInfo();
        if (deviceInfos != null && deviceInfos.size() > 0) {
            for (BLDeviceInfo deviceInfo : deviceInfos) {
                if (TextUtils.isEmpty(deviceInfo.getFamilyId()) && deviceInfo.getBlType() == 0) {
                    BLDNADevice dnaDevice = BLModelUtil.toDNADevice(deviceInfo);
                    BLLocalFamilyManager.getInstance().mLocalDnaDevice = dnaDevice;
                    break;
                }
            }
        }
    }

    @OnClick({R.id.btn_back, R.id.tv_back})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.btn_back:
                doBack();
                break;
            case R.id.tv_back:
                doBack();
                break;
        }
    }


    private void initRecycleView() {
        Context context = getContext();
        mAdapter = new ManageBLFamilyAdapter(context);
        mRecyclerView.setAdapter(mAdapter);
        mLayoutManager = new LinearLayoutManager(context);
        mRecyclerView.setLayoutManager(mLayoutManager);
        mRecyclerView.addItemDecoration(new DividerItemDecoration(getContext(), DividerItemDecoration.VERTICAL));
        mAdapter.setManageBLFamilyListener(this);
    }


    private void bindFamily() {
        BLLocalFamilyManager familyManager = BLLocalFamilyManager.getInstance();
        if (!familyManager.checkAppState()) {
            return;
        }
        if (mFamily == null) {
            toast("当前没有可绑定网关的家庭");
            return;
        }
        if (familyManager.mLocalDnaDevice == null) {
            toast("当前没有可绑定网关的设备");
            return;
        }
        familyManager.setBLFamilyListener((success, error, msg) -> {
            showUnBinderLoading = true;
            if (success) {
                refreshListData();
            }
        });
        familyManager.showLoading("正在绑定网关，请稍等...");
        MyThreadManager.getInstance().doTask(() -> {
            familyManager.createBLFamily(mFamily);
        });
    }

    @Override
    public void onClickBindItem(int position) {
        Log.i(TAG, "onClickBindItem: position = " + position);
        BLLocalFamilyManager familyManager = BLLocalFamilyManager.getInstance();
        boolean appState = familyManager.checkAppState();
        if (!appState) {
            return;
        }
        Family unBindFamily = null;
        for (Family family : mAdapter.getAllData()) {
            if (!TextUtils.isEmpty(family.getBlFamilyId())) {
                unBindFamily = family;
                break;
            }
        }
        showUnBinderLoading = false;
        unBindFamily(unBindFamily);
        Family bindFamily = mAdapter.getItem(position);
        mFamily = bindFamily;
        if (familyManager.mLocalDnaDevice == null) {
            toast("没有网关设备");
            Log.e(TAG, "onClickBindItem: familyManager.mLocalDnaDevice == null");
            return;
        }
        bindFamily();
    }
    private void unBindFamily(Family unBindFamily) {
        if (unBindFamily == null || TextUtils.isEmpty(unBindFamily.getBlFamilyId())) {
            return;
        }
        String blFamilyId = unBindFamily.getBlFamilyId();
        String familyId = unBindFamily.getFamilyId();
        if (TextUtils.isEmpty(blFamilyId)) {
            return;
        }
        unBindFamily.setBlType(0);
        unBindFamily.setBlFamilyId("");
        new FamilyDao(getContext()).updateFamily(unBindFamily);
        deleteFamilyBLDeviceInfos(familyId);
        mAdapter.notifyDataSetChanged();

        BLLocalFamilyManager familyManager = BLLocalFamilyManager.getInstance();

        if (showUnBinderLoading) {
            familyManager.showLoading("正在解绑网关，请稍等...");
        }
        MyThreadManager.getInstance().doTask(() -> {
            BLFamilyAllInfo familyAllInfo = familyManager.queryBLFamilyAllInfoTask(blFamilyId);
            if (familyAllInfo == null || familyAllInfo.getFamilyInfo() == null) {
                return;
            }
            BLFamilyInfo familyInfo = familyAllInfo.getFamilyInfo();
            BLBaseResult delFamilyResult = BLFamily.delFamily(familyInfo.getFamilyId(), familyInfo.getFamilyVersion());
            showBLBaseResultLog(delFamilyResult, "delFamilyResult:" + familyInfo.getFamilyName());
            if (delFamilyResult != null && delFamilyResult.succeed()) {
                if (showUnBinderLoading) {
                    familyManager.toast("解绑家庭成功");
                }
            }
            if (showUnBinderLoading) {
                familyManager.dismissLoading();
            }
        });
    }

    @Override
    public void onClickUnBindItem(int position) {
        BLLocalFamilyManager blLocalFamilyManager = BLLocalFamilyManager.getInstance();
        boolean appState = blLocalFamilyManager.checkAppState();
        if (!appState) {
            return;
        }
        Log.i(TAG, "onClickUnBindItem: position = " + position);
        Family family = mAdapter.getItem(position);
        unBindFamily(family);
    }

    private void deleteFamilyBLDeviceInfos(String familyId) {
        BLDeviceInfoDao deviceInfoDao = new BLDeviceInfoDao(getContext());
        List<BLDeviceInfo> familyBLDeviceInfos = deviceInfoDao.getFamilyBLDeviceInfos(familyId, 0);
        if (familyBLDeviceInfos != null && familyBLDeviceInfos.size() > 0) {
            BLDeviceInfo gatewayDevice = familyBLDeviceInfos.get(0);
            gatewayDevice.setFamilyId("");
            deviceInfoDao.update(gatewayDevice);
        }
        deviceInfoDao.deleteFamilyBLDeviceInfos(familyId);
    }
}
